/*
 * Activiti Modeler component part of the Activiti project
 * Copyright 2005-2014 Alfresco Software, Ltd. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

/*
 * Assignment
 */
var KisBpmAssignmentCtrl = ['$scope', '$modal', function ($scope, $modal) {

    // Config for the modal window
    var opts = {
        template: 'editor-app/configuration/properties/assignment-popup.html?version=' + Date.now(),
        scope: $scope
    };

    // Open the dialog
    $modal(opts);
}];

var KisBpmAssignmentPopupCtrl = ['$scope', '$http', function ($scope, $http) {

// Put json representing assignment on scope
    if ($scope.property.value !== undefined && $scope.property.value !== null
        && $scope.property.value.assignment !== undefined
        && $scope.property.value.assignment !== null) {
        $scope.assignment = $scope.property.value.assignment;
    } else {
        $scope.assignment = {};
    }

    $scope.popup = {
        assignment: {
            assignee: undefined,
            candidateUsers: [],
            candidateUserField: '',
            candidateGroups: [],
            candidateGroupField: '',
            assignmentType: [],
            assignmentTypeField: '',
            groupType: [],
            groupTypeField: '',
            companyId: [],
            companyIdField: ''
        }
    };

    //候选人或代理人
    $scope.primaryKey = "userId";
    //标识已选中
    $scope.selectedItems = [];

    if ($scope.assignment.assignee) {
        $scope.popup.assignment.assignee = $scope.assignment.assignee;
    }

    if ($scope.assignment.assignmentType && $scope.assignment.assignmentType.length > 0) {
        for (let i = 0; i < $scope.assignment.assignmentType.length; i++) {
            $scope.popup.assignment.assignmentType.push($scope.assignment.assignmentType[i]);
            $scope.popup.assignment.assignmentTypeField += (i === 0 ? '' : ',') + $scope.assignment.assignmentType[i].value;
        }
    }

    if ($scope.assignment.groupType && $scope.assignment.groupType.length > 0) {
        for (let i = 0; i < $scope.assignment.groupType.length; i++) {
            $scope.popup.assignment.groupType.push($scope.assignment.groupType[i]);
            $scope.popup.assignment.groupTypeField += (i === 0 ? '' : ',') + $scope.assignment.groupType[i].value;
        }
    }

    if ($scope.assignment.companyId && $scope.assignment.companyId.length > 0) {
        for (let i = 0; i < $scope.assignment.companyId.length; i++) {
            $scope.popup.assignment.companyId.push($scope.assignment.companyId[i]);
            $scope.popup.assignment.companyIdField += (i === 0 ? '' : ',') + $scope.assignment.companyId[i].value;
        }
    }

    if ($scope.assignment.candidateUsers && $scope.assignment.candidateUsers.length > 0) {
        for (let i = 0; i < $scope.assignment.candidateUsers.length; i++) {
            $scope.popup.assignment.candidateUsers.push($scope.assignment.candidateUsers[i]);
            $scope.selectedItems.push({userId: $scope.assignment.candidateUsers[i].value});
            $scope.popup.assignment.candidateUserField += (i === 0 ? '' : ',') + $scope.assignment.candidateUsers[i].text;
        }
    }

    if ($scope.assignment.candidateGroups && $scope.assignment.candidateGroups.length > 0) {
        for (let i = 0; i < $scope.assignment.candidateGroups.length; i++) {
            $scope.popup.assignment.candidateGroups.push($scope.assignment.candidateGroups[i]);
            $scope.popup.assignment.candidateGroupField += (i === 0 ? '' : ',') + $scope.assignment.candidateGroups[i].value;
        }
    }

    $scope.save = function () {
        $scope.assignment.assignee = $scope.popup.assignment.assignee;
        $scope.assignment.candidateUsers = $scope.popup.assignment.candidateUsers;
        $scope.assignment.candidateGroups = $scope.popup.assignment.candidateGroups;
        $scope.assignment.assignmentType = $scope.popup.assignment.assignmentType;
        $scope.assignment.groupType = $scope.popup.assignment.groupType;
        $scope.assignment.companyId = $scope.popup.assignment.companyId;
        $scope.property.value = {};
        $scope.property.value.assignment = $scope.assignment;

        $scope.updatePropertyInModel($scope.property);
        $scope.close();
    };

    // Close button handler
    $scope.close = function () {
        $scope.property.mode = 'read';
        $scope.$hide();
    };


    //******************************自定义选择代理人，候选人，候选组******************************
    // 参数初始化
    $scope.treeData = [];//下拉树数据
    $scope.gridData = [];//表格数据
    $scope.gridDataName = 'gridData';
    $scope.selectTitle = '选择候选人';
    $scope.selectGroupTitle = '岗位名称';
    $scope.columnData = [];//表格列数据
    $scope.columnDataName = 'columnData';
    $scope.selectType = 1;//0-代理人，1-候选人，2-候选组
    $scope.totalServerItems = 0;//表格总条数
    // 分页初始化
    $scope.pagingOptions = {
        pageSizes: [10, 20, 30],//page 行数可选值
        pageSize: 10, //每页行数
        currentPage: 1, //当前显示页数
    };
    // 职位列表
    $scope.positionData = [];
    $scope.isCandidate = true;
    // 当前页全选
    $scope.allSelected = false;
    $scope.isShow = true;
    // 选人方案
    $scope.assignmentTypeOption = [
        {
            label: "具体角色/岗位/部门中的人员",
            value: 1
        },
        {
            label: "指定人员",
            value: 2
        },
        {
            label: "提交人所在公司领导",
            value: 3
        },
    ];

    // 选人类型
    $scope.assignmentType = $scope.assignment.assignmentType && $scope.assignment.assignmentType.length > 0 ? $scope.assignment.assignmentType[0].value : undefined;
    // 组类型
    $scope.groupType = $scope.assignment.groupType && $scope.assignment.groupType.length > 0 ? $scope.assignment.groupType[0].value : -1;
    // 岗位ID/角色ID/部门ID
    $scope.groupId = $scope.assignment.groupType && $scope.assignment.groupType.length > 0 && $scope.assignment.candidateGroups.length > 0 ? $scope.assignment.candidateGroups[0].value : -1;
    // 公司ID
    $scope.companyId = $scope.assignment.companyId && $scope.assignment.companyId.length > 0 ? $scope.assignment.companyId[0].value : -1;
    // 职位ID
    $scope.positionId = $scope.assignment.companyId && $scope.assignment.companyId.length > 0 && $scope.assignment.candidateGroups.length > 0 ? $scope.assignment.candidateGroups[0].value : -1;

    //组类型
    $scope.groupTypeOption = [
        {
            label: "岗位",
            value: 1
        },
        {
            label: "角色",
            value: 2
        },
        {
            label: "部门",
            value: 3
        },
    ];

    //数据监视
    $scope.dataWatch = function () {
        //分页数据监视
        $scope.$watch('pagingOptions', function (newValue, oldValue) {
            $scope.getPagedDataAsync($scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize, $scope.groupType, $scope.groupId);
        }, true);
        //组类型切换监视
        $scope.$watch('groupType', function (newValue, oldValue) {
            if (newValue !== -1) {
                $scope.groupType = newValue;
                $scope.getTreeDataAsync($scope.assignmentType, $scope.groupType);
            }
        }, true);
        //岗位、角色、部门切换监视
        $scope.$watch('groupId', function (newValue, oldValue) {
            if (newValue !== -1) {
                $scope.getPagedDataAsync($scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize, $scope.groupType, $scope.groupId);
            }
        }, true);
        //公司切换监视
        $scope.$watch('companyId', function (newValue, oldValue) {
            if (newValue !== -1) {
                $scope.companyId = newValue;
                $scope.getTreeDataAsync($scope.assignmentType, 1);
            }
        }, true);
        //职位切换监视
        $scope.$watch('positionId', function (newValue, oldValue) {
            if (newValue !== -1) {
                $scope.positionId = newValue;
                $scope.postId = $scope.companyId + ":" + newValue;
                $scope.getPagedDataAsync($scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize, 1, $scope.postId);
            }
        }, true);
    };

    $scope.dataWatch();

    $scope.initPage = function (newValue, oldValue) {
        if (newValue !== oldValue) {
            $scope.pagingOptions.currentPage = 1;
            $scope.getPagedDataAsync($scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize, $scope.groupType, $scope.groupId);
        }
    }
    /**
     * assignmentType : 选人方式类型
     * groupType : 组类型
     * **/
    $scope.getTreeDataAsync = function (assignmentType, groupType) {
        let url = "";

        if (assignmentType === 1) {
            // 具体角色/岗位/部门中的内容
            if (groupType === 3) {
                url = '/editor/idGroup/deptTree'; // 获取部门数据接口
            } else if (groupType === 2) {
                url = '/editor/idGroup/roleTree'; // 获取角色数据接口
            } else if (groupType === 1) {
                url = '/editor/idGroup/postTree'; // 获取岗位数据接口
            }
        } else if (assignmentType === 3) {
            url = '/editor/idGroup/deptTree'; // 获取部门数据接口

            if (groupType === 1) {
                let getUrl = '/editor/idGroup/getPostByDept';

                $http({
                    method: 'GET',
                    url: ACTIVITI.CONFIG.contextRoot + getUrl,
                    params: {
                        'deptId': $scope.companyId
                    }
                }).then(function successCallback(response) {
                    $scope.positionData = response.data.data;
                }, function errorCallback(response) {
                    // 请求失败执行代码
                    $scope.positionData = [];
                });
            }
        }

        $http({
            method: 'GET',
            url: ACTIVITI.CONFIG.contextRoot + url
        }).then(function successCallback(response) {
            $scope.treeData = response.data.data;
        }, function errorCallback(response) {
            // 请求失败执行代码
            $scope.treeData = [];
        });
    }

    //异步请求表格数据
    $scope.getPagedDataAsync = function (pageNum, pageSize, groupType, groupId) {
        var url = '/editor/idUser/list'; // 获取用户数据接口
        $scope.columnData = $scope.userColumns;

        $http({
            method: 'POST',
            url: ACTIVITI.CONFIG.contextRoot + url,
            params: {
                'pageNum': pageNum,
                'pageSize': pageSize,
                'groupType': groupType,
                'groupId': groupId
            },
        }).then(function successCallback(response) {
            $scope.gridData = response.data.rows;
            $scope.totalServerItems = response.data.total;
            $scope.allSelected = $scope.isAllExist();
            setTimeout(() => {
                $scope.$apply()
            })
        }, function errorCallback(response) {
            // 请求失败执行代码
            $scope.gridData = [];
            $scope.totalServerItems = 0;
        });
    };

    // 处理候选人数据
    $scope.handleUsers = function (obj, isAllAdd) {
        let notExist = true;
        for (let i = 0; i < $scope.popup.assignment.candidateUsers.length; i++) {
            if ($scope.popup.assignment.candidateUsers[i].value === obj.userId) {
                if (isAllAdd) {
                    notExist = false;
                    break;
                } else {
                    $scope.popup.assignment.candidateUsers.splice(i, 1);
                    $scope.gridOptions.selectedItems.splice(i, 1);
                    $scope.selectedItems.splice(i, 1);
                    notExist = false;
                    break;
                }
            }
        }
        if (notExist) {
            $scope.popup.assignment.candidateUsers.push({value: obj.userId, text: obj.nickName});
            $scope.selectedItems.push({userId: obj.userId});
            $scope.gridOptions.selectedItems.push({userId: obj.userId});
        }
        $scope.popup.assignment.candidateUserField = '';
        for (let i = 0; i < $scope.popup.assignment.candidateUsers.length; i++) {
            $scope.popup.assignment.candidateUserField += (i === 0 ? '' : ',') + $scope.popup.assignment.candidateUsers[i].text;
        }
    };

    // 处理候选组数据
    $scope.handleGroups = function (data) {
        $scope.popup.assignment.candidateGroups = [];
        $scope.popup.assignment.candidateGroups.push({value: data});
        $scope.popup.assignment.candidateGroupField = data;
    };

    // 处理选人类型数据
    $scope.handleAssignType = function (data) {
        $scope.popup.assignment.assignmentType = [];
        $scope.popup.assignment.assignmentType.push({value: data});
        $scope.popup.assignment.assignmentTypeField = data;

        if ($scope.assignmentType === 1) {
            $scope.popup.assignment.companyId = [];
            $scope.popup.assignment.companyIdField = '';
        } else if ($scope.assignmentType === 2) {
            $scope.popup.assignment.groupType = [];
            $scope.popup.assignment.companyId = [];
            $scope.popup.assignment.candidateGroups = [];
            $scope.popup.assignment.groupTypeField = '';
            $scope.popup.assignment.companyIdField = '';
            $scope.popup.assignment.candidateGroupField = '';
        } else if ($scope.assignmentType === 3) {
            $scope.popup.assignment.groupType = [];
            $scope.popup.assignment.groupTypeField = '';
        }
    };

    // 处理组类型数据
    $scope.handleGroupType = function (data) {
        $scope.popup.assignment.groupType = [];
        $scope.popup.assignment.groupType.push({value: data});
        $scope.popup.assignment.groupTypeField = data;
    };

    // 处理公司数据
    $scope.handleCompanyId = function (data) {
        $scope.popup.assignment.companyId = [];
        $scope.popup.assignment.companyId.push({value: data});
        $scope.popup.assignment.companyIdField = data;
    };

    //表格属性配置
    $scope.gridOptions = {
        data: $scope.gridDataName,
        multiSelect: true,//不可多选
        enablePaging: true,
        pagingOptions: $scope.pagingOptions,
        totalServerItems: 'totalServerItems',
        i18n: 'zh-cn',
        showFooter: true,
        showSelectionCheckbox: true,
        columnDefs: $scope.columnDataName,
        primaryKey: $scope.primaryKey,
        selectedItems: $scope.selectedItems,
        checkboxHeaderTemplate: '<input class="ngSelectionHeader" type="checkbox" ng-show="multiSelect" ng-model="allSelected" ng-click="toggleSelectAll(!allSelected)"/>',
        afterSelectionChange: function (event) {
            if (Array.isArray(event)) {
                event.forEach((item) => {
                    $scope.handleBySelect(item, item.selected);
                })
            } else {
                $scope.handleBySelect(event, event.selected);
            }

            $scope.allSelected = $scope.isAllExist();
            setTimeout(() => {
                $scope.$apply()
            })
        },
        beforeSelectionChange: function (rowItem, event) {
            return true;
        }
    };

    $scope.handleBySelect = function (event, isAllAdd) {
        let data = event.entity.userId;

        if ($scope.selectType === 0) { // 选代理人
            if ($scope.popup.assignment.assignee === data) {
                $scope.popup.assignment.assignee = '';
            } else {
                $scope.popup.assignment.assignee = data;
            }
        } else if ($scope.selectType === 1) { // 候选人
            $scope.handleUsers(event.entity, isAllAdd);
        } else if ($scope.selectType === 2) { // 候选组
            $scope.handleGroups(event.entity.deptId);
        }
    }

    $scope.isAllExist = function () {
        if ($scope.gridData.length === 0) {
            return false
        } else {
            return $scope.gridData.every(item =>
                $scope.gridOptions.selectedItems.some(itemInfo =>
                    item.userId === itemInfo.userId
                ));
        }

    }

    //选择用户时表头
    $scope.userColumns = [
        {
            field: 'userId',
            type: 'number',
            displayName: '用户Id',
            minWidth: 100,
            width: '20%'
        },
        {
            field: 'nickName',
            displayName: '姓名',
            minWidth: 100,
            width: '20%'
        },
        {
            field: 'mobile',
            displayName: '手机号码',
            minWidth: 100,
            width: '30%'
        },
        {
            field: 'email',
            displayName: '邮箱',
            minWidth: 100,
            width: '30%'
        }
    ];

    // 选人方式发生变化
    $scope.assignmentChange = function (data) {
        $scope.assignmentType = data;
        // 组类型
        $scope.groupType = -1;
        $scope.groupId = -1;
        $scope.handleAssignType(data);
        $scope.resetGrid();

        if ($scope.assignmentType === 2) {
            $scope.getPagedDataAsync($scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize, -1, -1);
        } else if ($scope.assignmentType === 3) {
            $scope.getTreeDataAsync($scope.assignmentType, 3);
        }
    }

    //切换组类型
    $scope.groupTypeChange = function (data) {
        $scope.groupType = data;
        $scope.groupId = -1;
        $scope.handleGroupType(data);
        $scope.resetGrid();

        if ($scope.groupType === 1) {
            $scope.selectGroupTitle = "岗位名称";
        } else if ($scope.groupType === 2) {
            $scope.selectGroupTitle = "角色名称";
        } else if ($scope.groupType === 3) {
            $scope.selectGroupTitle = "部门名称";
        }

        if ($scope.assignmentType === 3) {
            $scope.getTreeDataAsync($scope.assignmentType, 1);
        } else {
            $scope.getTreeDataAsync($scope.assignmentType, $scope.groupType);
        }


    };

    // 切换岗位/角色/部门
    $scope.groupChange = function (data) {
        $scope.groupId = data;
        $scope.handleGroups(data);
        $scope.resetGrid();
        $scope.getPagedDataAsync($scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize, $scope.groupType, $scope.groupId);
    }

    // 切换所属公司
    $scope.companyChange = function (data) {
        $scope.companyId = data;
        $scope.handleCompanyId(data);
        $scope.resetGrid();
        $scope.getTreeDataAsync($scope.assignmentType, 1);
    }

    // 切换职位
    $scope.positionChange = function (data) {
        $scope.positionId = data;
        $scope.postId = $scope.companyId + ":" + data;
        $scope.handleGroups(data);
        $scope.resetGrid();
        $scope.getPagedDataAsync($scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize, 1, $scope.postId);
    }

    // 重置
    $scope.resetGrid = function () {
        $scope.gridOptions.selectedItems.forEach((item, index) => {
            $scope.gridOptions.selectItem(index, false);
        })
        $scope.pagingOptions.currentPage = 1;
        $scope.gridData = [];
        $scope.gridOptions.selectedItems = [];
        $scope.selectedItems = [];
        $scope.totalServerItems = 0;
        $scope.popup.assignment.candidateUsers = [];
        $scope.popup.assignment.candidateUserField = '';

        $scope.allSelected = $scope.isAllExist();
        setTimeout(() => {
            $scope.$apply()
        })
    }

}];

